import { get } from 'lodash';
import { regionData } from 'element-china-area-data';

const getRegionDataList = () => {
  const reduceData = list => {
    if (Array.isArray(list)) {
      return list.map(item => {
        const { value, label } = item;
        const children = reduceData(item.children);
        let result = {
          value: value,
          label: label
        };
        if (children && children.length > 0) {
          result = {
            ...result,
            children: children
          };
        }
        return result;
      });
    } else {
      return list;
    }
  };
  return reduceData(regionData);
}

export default {
  data() {
    return { region: [], backRegion: [], regionDataList: getRegionDataList() };
  },
  computed: {

  },
  methods: {
    getRegionDetail(region) {
      let detailData = [];
      region.reduce((prev, cur, index) => {
        const result = prev.find(item => item.value == cur);
        if (result) {
          detailData[index] = result
        }
        return get(result, 'children', []);
      }, this.regionDataList);
      return detailData;
    },
    getRegionNameList(regionDetail) {
      return regionDetail.map(item => item.label)
    },
    transformRegionByLabel(regionNameList) {
      let valueData = [];
      regionNameList.reduce((prev, cur, index) => {
        const result = prev.find(item => item.label == cur);
        if (result) {
          valueData[index] = result.value
        }
        return get(result, 'children', []);
      }, this.regionDataList);
      return valueData;
    },
    formatterImages(imgs) {
      if (imgs.indexOf('[') == 0) {
        return JSON.parse(imgs);
      } else {
        return imgs.split(',');
      }
    }
  }
};
